//
//  MosaicLayout.swift
//  CoolImageFound
//
//  Created by  iBrother 李彦兵 on 2018/6/9.
//  Copyright © 2018  iBrother 李彦兵. All rights reserved.
//

import UIKit

class MosaicLayout: UICollectionViewLayout {
    var contentBounds = CGRect.zero
    var cachedAttributes = [UICollectionViewLayoutAttributes]()
    
    override func prepare() {
        super.prepare()
        guard let cv = collectionView else { return }
        
        cachedAttributes.removeAll()
//        contentBounds = CGRect(origin: .zero, size: cv.bounds.size)
        contentBounds = CGRect(origin: CGPoint(x: 10, y: 20), size: cv.bounds.size)
        
        createAttributes()
    }
    
    func createAttributes() {
//        cachedAttributes.append(UICollectionViewLayoutAttributes.init())
//        cachedAttributes.append(CGSize(width: 100, height: 200))
    }
    
    override var collectionViewContentSize: CGSize {
        return contentBounds.size
    }
    
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        guard let cv = collectionView else { return false }
        return !newBounds.size.equalTo(cv.bounds.size)
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return cachedAttributes[indexPath.item]
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        return cachedAttributes.filter({ (attributes: UICollectionViewLayoutAttributes) -> Bool in
            return rect.intersects(attributes.frame)
        })
    }
}
